package com.dd.dus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.entity.users.DRole;
import com.dd.dc.entity.users.DUserRoleRelation;
import com.dd.dus.mapper.DRoleMapper;
import com.dd.dus.mapper.DUserRoleRelationMapper;
import com.dd.dus.service.IDRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author JueDream
 * @since 2021-03-12
 */
@Service
public class DRoleServiceImpl extends ServiceImpl<DRoleMapper, DRole> implements IDRoleService {

    @Autowired
    DRoleMapper roleMapper;

    @Autowired
    DUserRoleRelationMapper userRoleRelationMapper;

    @Override
    public List<DRole> findRoleByUserId(Integer userId) {
        userId = Optional.ofNullable(userId).orElse(0);
        List<DRole> roles = new ArrayList<>();
        if (userId > 0) {
            // 根据用户查询关系表
            DUserRoleRelation userRoleRelation = new DUserRoleRelation().setUserId(userId);
            QueryWrapper queryWrapper = new QueryWrapper(userRoleRelation);
            List<DUserRoleRelation> userRoleRelations = userRoleRelationMapper.selectList(queryWrapper);
            // 根据角色id查询
            List<Integer> roleIds = Optional.ofNullable(userRoleRelations).orElse(new ArrayList<>())
                    .stream().map(role -> role.getRoleId()).collect(Collectors.toList());
            if (roleIds.size() > 0){
                roles = roleMapper.selectBatchIds(roleIds);
            }
        }else{
            // 查询所有角色信息
            roles = roleMapper.selectList(new QueryWrapper(new DRole().setDelFlg(0)));
        }
        return roles;
    }

    @Override
    public Page<DRole> queryRoleList(int page, int limit, String roleName) {
        Page<DRole> roleIPage = new Page<>(page, limit);
        LambdaQueryWrapper<DRole> queryWrapper = new LambdaQueryWrapper<DRole>();
        queryWrapper.like(DRole::getRoleName, roleName);
        roleIPage = roleMapper.selectPage(roleIPage, queryWrapper);
        roleIPage.setTotal(roleIPage.getRecords().size());
        return roleIPage;
    }

    @Override
    public Integer insert(DRole role) {
        roleMapper.insert(role);
        return role.getRoleId();
    }
}
